package main

import (
	"io"
	"math/rand"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	route := gin.New()
	route.LoadHTMLGlob("./*.html")

	route.GET("/sse", func(ctx *gin.Context) {
		ch := make(chan int)
		go func() {
			for i := 0; i < 10; i++ {
				ch <- rand.Intn(89999) + 10000
				time.Sleep(time.Second)
			}
			ch <- -1
		}()
		ctx.Stream(func(io.Writer) bool {
			select {
			case v := <-ch:
				if v > 0 {
					ctx.SSEvent("", v)
					return true
				}
				return false
			}
		})
		ctx.SSEvent("close", nil)
	})

	route.GET("/", func(ctx *gin.Context) {
		ctx.HTML(http.StatusOK, "index.html", make(map[string]string))
	})

	route.Run(":8090")
}
